package n3_临界区critical_zone;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用面向对象思想 改进 Synchronized
 */
@Slf4j(topic = "c.T2")
public class T3_面向对象思想_加锁synchronized {

    public static void main(String[] args) throws InterruptedException {

        final Room room = new Room();
        log.debug("----- begin -----");

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {

                room.increment();

            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {

                room.decrement();

            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("----- end 最终结果是：{} -----",room.getCounter());


    }
}

class Room{

    private int counter = 0;

/*
    public int getCounter() {
        synchronized (this) {
            return counter;
        }
    }

    public void increment(){

        synchronized (this){
            counter ++;
        }

    }
    public void decrement(){

        synchronized (this){
            counter --;
        }
    }

    下面是 改进后的 方法
    */
    public synchronized int getCounter() {
            return counter;
    }

    public synchronized void increment(){

            counter ++;
    }
    public synchronized void decrement(){

            counter --;
    }

}
